package com.barry.oscheckpoint;

import java.io.File;
import java.text.DecimalFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.os.Environment;
 
public class WriteXMLFile {
	
	static Document doc;
	
	public static void CreateXMLFile(String fileName, String[] cp) {
		 
		  try {
			   CreateDocAndRootNode();
		  }
			  catch (Exception tfe) {
					tfe.printStackTrace();
				  }
	}
	
	
	public static void CreateDocAndRootNode() {
		 
		  try {
			    if (doc != null){
			    	return;
			    }
				DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		 
				// root elements
			    doc = docBuilder.newDocument();
				Element r = doc.createElement("r");
				doc.appendChild(r);
				r.setAttribute("n", "Bob Graham Round");
		  }
		  catch (ParserConfigurationException pce) {
				pce.printStackTrace();
			  } 
		  catch (Exception tfe) {
				tfe.printStackTrace();
			  }
		}	
	
	public static void WriteXML(String fileName) {
		  try {
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(doc);
					StreamResult result = new StreamResult(new File(Environment.getExternalStorageDirectory().getPath() + "/OSCheckPoint/" + fileName));
				// Output to console for testing
				// StreamResult result = new StreamResult(System.out);
		 
				transformer.transform(source, result);
		  }
		  catch (Exception ex) {
				ex.printStackTrace();
			  } 
		}	
 
	public static void CreateCheckPoint(String[] cp) {
		 try {
				// cp elements
				Element c = doc.createElement("c");
				doc.getFirstChild().appendChild(c);
				//lat
				String osGrid = cp[0].trim();
				double[] latLon = LonLatOS.OSGridToLatLong(osGrid);
				c.setAttribute("a", new DecimalFormat("#.#######").format(latLon[0]));
				//lon
				c.setAttribute("o", new DecimalFormat("#.#######").format(latLon[1]));
				//lbl
				c.setAttribute("l",cp[1]);
			  } 
			  catch (Exception pce) {
				pce.printStackTrace();
			  } 
	}
}